package com.hsl.housaileibot001.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hsl.housaileibot001.common.PageRequest;
import com.hsl.housaileibot001.common.Result;
import com.hsl.housaileibot001.model.InterviewQuestion;
import com.hsl.housaileibot001.model.vo.TagVO;
import com.hsl.housaileibot001.service.InterviewQuestionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 面试题目控制器
 */
@RestController
@RequestMapping("/interview-questions")
@RequiredArgsConstructor
@Tag(name = "面试题目管理")
public class InterviewQuestionController {

    private final InterviewQuestionService interviewQuestionService;

    /**
     * 分页查询面试题目
     *
     * @param pageRequest 分页请求参数
     * @param title 标题关键字（模糊搜索）
     * @param tags 标签列表（精确匹配，多个标签用逗号分隔）
     * @return 分页结果
     */
    @Operation(summary = "分页查询面试题目")
    @PostMapping("/page")
    public Result<Page<InterviewQuestion>> pageInterviewQuestions(
            @RequestBody PageRequest pageRequest,
            @Parameter(description = "标题关键字") @RequestParam(required = false) String title,
            @Parameter(description = "标签列表") @RequestParam(required = false) String tags) {
        Page<InterviewQuestion> page = new Page<>(pageRequest.getPageNum(), pageRequest.getPageSize());
        pageRequest.applyOrder(page);
        interviewQuestionService.pageWithSearch(page, title, tags);
        return Result.success(page);
    }

    /**
     * 根据ID查询面试题目
     *
     * @param id 面试题目ID
     * @return 面试题目信息
     */
    @Operation(summary = "根据ID查询面试题目")
    @GetMapping("/{id}")
    public Result<InterviewQuestion> getInterviewQuestionById(
            @Parameter(description = "面试题目ID") @PathVariable Long id) {
        InterviewQuestion interviewQuestion = interviewQuestionService.getById(id);
        if (interviewQuestion == null) {
            return Result.error("未找到指定的面试题目");
        }
        return Result.success(interviewQuestion);
    }

    /**
     * 新增面试题目
     *
     * @param interviewQuestion 面试题目信息
     * @return 是否成功
     */
    @Operation(summary = "新增面试题目")
    @PostMapping
    public Result<Boolean> createInterviewQuestion(@RequestBody InterviewQuestion interviewQuestion) {
        boolean success = interviewQuestionService.save(interviewQuestion);
        if (success) {
            return Result.success(true);
        } else {
            return Result.error("新增面试题目失败");
        }
    }

    /**
     * 修改面试题目
     *
     * @param interviewQuestion 面试题目信息
     * @return 是否成功
     */
    @Operation(summary = "修改面试题目")
    @PutMapping
    public Result<Boolean> updateInterviewQuestion(@RequestBody InterviewQuestion interviewQuestion) {
        boolean success = interviewQuestionService.updateById(interviewQuestion);
        if (success) {
            return Result.success(true);
        } else {
            return Result.error("修改面试题目失败");
        }
    }

    /**
     * 修改面试题状态
     * @param id 面试题ID
     * @param status 状态（ACTIVE/INACTIVE）
     * @return 是否成功
     */
    @Operation(summary = "修改面试题状态")
    @PutMapping("/status")
    public Result<Boolean> updateInterviewQuestionStatus(@RequestParam Long id,
                                                         @RequestParam String status) {
        boolean success = interviewQuestionService.updateStatus(id, status);
        if (success) {
            return Result.success(true);
        } else {
            return Result.error("修改面试题状态失败");
        }
    }

    /**
     * 批量删除面试题目
     *
     * @param ids 面试题目ID列表
     * @return 是否成功
     */
    @Operation(summary = "批量删除面试题目")
    @DeleteMapping("/batch")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Boolean> deleteInterviewQuestions(@RequestBody List<Long> ids) {
        boolean success = interviewQuestionService.removeBatchByIds(ids);
        if (success) {
            return Result.success(true);
        } else {
            return Result.error("批量删除面试题目失败");
        }
    }

    /**
     * 导入Excel文件
     *
     * @param file Excel文件
     * @return 导入结果
     */
    @Operation(summary = "导入Excel文件")
    @PostMapping("/import")
    public Result<String> importExcel(
            @Parameter(description = "Excel文件") @RequestParam("file") MultipartFile file) {
        try {
            String result = interviewQuestionService.importFromExcelWithDTO(file);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("导入失败：" + e.getMessage());
        }
    }

    /**
     * 分页获取标签列表（按标签数量降序）
     *
     * @param pageRequest 分页请求参数
     * @return 分页结果
     */
    @Operation(summary = "分页获取标签列表（按标签数量降序）")
    @PostMapping("/tags/page")
    public Result<IPage<TagVO>> pageTags(@RequestBody PageRequest pageRequest) {
        Page<TagVO> page = new Page<>(pageRequest.getPageNum(), pageRequest.getPageSize());
        return Result.success(interviewQuestionService.pageTagList(page));
    }
}